package com.molichuxing.services.infrastructure.service.impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.dto.TabDto;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.services.business.dto.response.GoodsSalesStatisticsBizDto;
import com.molichuxing.services.business.dto.response.OrderCarInfoAppDto;
import com.molichuxing.services.contants.OrderStatusConst;
import com.molichuxing.services.infrastructure.bean.OrderSubscribeBean;
import com.molichuxing.services.infrastructure.convertor.Convert;
import com.molichuxing.services.infrastructure.dao.OrderSubscribeMapper;
import com.molichuxing.services.infrastructure.dto.request.create.OrderSubscribeCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.*;
import com.molichuxing.services.infrastructure.dto.response.OrderSubscribeDto;
import com.molichuxing.services.infrastructure.service.OrderSubscribeService;
import com.molichuxing.services.property.OrderExclusivelStatusEnum;
import com.molichuxing.services.property.OrderListTypeEnum;
import com.molichuxing.services.property.OrderSubscribeStatusEnum;
import com.molichuxing.services.property.OrderTypeEnum;
import com.molichuxing.services.utils.OrderUtil;
import com.molichuxing.services.utils.TabUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订阅里程订单基础服务
 *
 * @author zoumingyu
 * @date 2019年8月13日
 */
@Service("orderSubscribeService")
public class OrderSubscribeServiceImpl implements OrderSubscribeService {
    private static final Logger logger = LoggerFactory.getLogger(OrderSubscribeServiceImpl.class);

    @Resource
    private OrderSubscribeMapper orderSubscribeMapper;

    /**
     * 订阅里程订单信息
     *
     * @param orderCode 订单号
     * @return
     */
    @Override
    public OrderSubscribeDto getOrderSubscribe(Long orderCode) {
        return Convert.toOrderSubscribeBeanDto(orderSubscribeMapper.getByOrderCode(orderCode));
    }

    /**
     * 查询订阅订单信息
     *
     * @param parentOrderCode      父订单号
     * @param orderSubscribeStatus 订单状态
     * @return
     */
    @Override
    public OrderSubscribeDto getOrderSubscribeByParent(Long parentOrderCode,
                                                       OrderSubscribeStatusEnum orderSubscribeStatus) {
        OrderSubscribeDto result = null;
        List<OrderSubscribeBean> orderSubscribes = orderSubscribeMapper.getByParentOrderCode(parentOrderCode,
                orderSubscribeStatus.getValue());
        if (orderSubscribes != null && !orderSubscribes.isEmpty()) {
            result = Convert.toOrderSubscribeBeanDto(orderSubscribes.get(0));
        }

        return result;
    }

    /**
     * 分页获取订阅里程订单信息
     *
     * @param params   listType：列表类型-enum <br />
     *                 orderStatus：订单状态-enum <br />
     *                 orderCode：订单号-long <br />
     *                 userIds：用户id-list <br />
     *                 storeIds：门店id-list <br />
     *                 orderTimeStart：下单开始时间-LocalDate <br />
     *                 orderTimeEnd：下单结束时间-LocalDate <br />
     *                 isHaveSuborder：有无续订-boolean
     * @param pageNum  页数
     * @param pageSize 每页条数
     * @return
     * @throws Exception
     */
    @Override
    public Paged<OrderSubscribeDto> getOrderList(Map<String, Object> params, int pageNum, int pageSize)
            throws Exception {
        // 拼接条件
        OrderSubscribeStatusEnum orderStatusEnum = ObjectCastUtil.castEmun(params.get("orderStatus"),
                OrderSubscribeStatusEnum.class);
        if (orderStatusEnum != null) {
            // 订单状态
            if (OrderSubscribeStatusEnum.TRADE_PASS.equals(orderStatusEnum)) {
                // 审核通过状态
                List<Integer> list = new ArrayList<>();
                for (OrderSubscribeStatusEnum orderSubscribeStatus : OrderStatusConst.CREDIT_PASS_SUBSCRIBE_STATUS) {
                    list.add(orderSubscribeStatus.getValue());
                }
                params.put("orderStatusList", list);
                params.remove("orderStatus");
            } else if (OrderSubscribeStatusEnum.TRADE_REJECTED.equals(orderStatusEnum)) {
                // 审核驳回状态
                OrderSubscribeStatusEnum refundStatusEnum = ObjectCastUtil.castEmun(params.get("refundStatus"),
                        OrderSubscribeStatusEnum.class);
                if (refundStatusEnum == null) {
                    List<Integer> list = new ArrayList<>();
                    for (OrderSubscribeStatusEnum orderSubscribeStatus : OrderStatusConst.CREDIT_REJECT_SUBSCRIBE_STATUS) {
                        list.add(orderSubscribeStatus.getValue());
                    }
                    params.put("orderStatusList", list);
                    params.remove("orderStatus");
                } else if (OrderSubscribeStatusEnum.TRADE_REJECTED.equals(refundStatusEnum)
                        || OrderSubscribeStatusEnum.TRADE_REFUND.equals(refundStatusEnum)
                        || OrderSubscribeStatusEnum.TRADE_FINISH.equals(refundStatusEnum)) {
                    // 待处理、退款中、已退款
                    params.put("orderStatus", refundStatusEnum.getValue());
                }
            } else {
                // 其他状态
                params.put("orderStatus", orderStatusEnum.getValue());
            }
        } else {
            // 订单列表类型
            OrderListTypeEnum listTypeEnum = ObjectCastUtil.castEmun(params.get("listType"), OrderListTypeEnum.class);
            params.put("orderStatusList", OrderUtil.getStatusList(OrderTypeEnum.SUBSCRIBE, listTypeEnum));
        }

        // 下单开始时间-LocalDateTime
        params.put("orderTimeStart", ObjectCastUtil.castLocalDateTimeStart(params.get("orderTimeStart")));
        // 下单结束时间-LocalDateTime
        params.put("orderTimeEnd", ObjectCastUtil.castLocalDateTimeEnd(params.get("orderTimeEnd")));

        long total = orderSubscribeMapper.getPageCount(params);
        List<OrderSubscribeBean> page = null;
        if (total > 0) {
            page = orderSubscribeMapper.getPage(params, pageNum, pageSize);
        }

        return new Paged<>(Convert.toOrderSubscribeBeanDto(page), total, pageSize);
    }

    /**
     * 根据用户id查询订阅里程订单信息
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<OrderSubscribeDto> getOrderListByUser(Integer userId) {
        return userId == null ? null : Convert.toOrderSubscribeBeanDto(orderSubscribeMapper.getByUser(userId, null));
    }

    /**
     * 根据用户id查询有效订单（未取消、未删除）
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<OrderSubscribeDto> getNormalByUser(Integer userId) {
        return userId == null ? null
                : Convert.toOrderSubscribeBeanDto(
                orderSubscribeMapper.getByUser(userId, OrderUtil.getNormalStatus(OrderTypeEnum.SUBSCRIBE)));
    }

    /**
     * 根据车辆id查询订阅里程订单信息
     *
     * @param carId 车辆id
     * @return
     */
    @Override
    public List<OrderSubscribeDto> getOrderListByCar(Integer carId) {
        return getOrderListByCar(carId, null);
    }

    /**
     * 根据车辆id查询订阅里程订单信息
     *
     * @param carId    车辆id
     * @param storeIds 门店ids
     * @return
     */
    @Override
    public List<OrderSubscribeDto> getOrderListByCar(Integer carId, List<Integer> storeIds) {
        List<OrderSubscribeDto> result = null;
        List<OrderSubscribeBean> dtoList = orderSubscribeMapper.getByCar(carId, storeIds);
        if (dtoList == null || dtoList.size() <= 0) {
            return result;
        }
        result = new ArrayList<>();
        for (OrderSubscribeBean bean : dtoList) {
            // 续订单，未支付或已取消的不显示
            if ((bean.getParentOrderCode() != null && bean.getParentOrderCode() > 0)
                    && (bean.getOrderStatus() == OrderSubscribeStatusEnum.TRADE_UNPAID.getValue()
                    || bean.getOrderStatus() == OrderSubscribeStatusEnum.TRADE_CANCELED.getValue())) {
                continue;
            }

            result.add(Convert.toOrderSubscribeBeanDto(bean));
        }

        return result;
    }

    /**
     * 统计每种状态下的数据量
     *
     * @param orderListType 列表类型枚举
     * @return
     */
    @Override
    public List<TabDto> getStatusStatistics(OrderListTypeEnum orderListType) {
        return this.getStatusStatistics(orderListType, null);
    }

    /**
     * 统计每种状态下的数据量
     *
     * @param orderListType 列表类型枚举
     * @param storeIds      门店ids
     * @return
     */
    @Override
    public List<TabDto> getStatusStatistics(OrderListTypeEnum orderListType, List<Integer> storeIds) {
        List<TabDto> result = new ArrayList<>();
        // 分组查询订单状态数量
        List<TabDto> tabDtoList = orderSubscribeMapper.getStatusStatistics(storeIds);

        List<OrderSubscribeStatusEnum> statusEnumList = null;
        if (OrderListTypeEnum.TRADE_LIST.equals(orderListType)) {
            // 交易列表查询订单状态
            statusEnumList = OrderStatusConst.TRADE_SUBSCRIBE_STATUS;
            result = TabUtil.subscribeTransform(statusEnumList, tabDtoList);
        } else if (OrderListTypeEnum.CREDIT_LIST.equals(orderListType)) {
            // 征信审核列表
            statusEnumList = OrderStatusConst.CREDIT_SUBSCRIBE_STATUS;
            result = TabUtil.subscribeCreditTransform(statusEnumList, tabDtoList);
        } else if (OrderListTypeEnum.RETURN_LIST.equals(orderListType)) {
            // 到期还车列表
            statusEnumList = OrderStatusConst.RETURN_SUBSCRIBE_STATUS;
            result = TabUtil.subscribeTransform(statusEnumList, tabDtoList);
        }

        return result;
    }

    /**
     * 根据用户id查询订单号
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<Long> getOrderCodeByUser(Integer userId) {
        return orderSubscribeMapper.getOrderCodeByUser(userId);
    }

    /**
     * 根据用户id查询订单号
     *
     * @param userIds 用户id
     * @return
     */
    @Override
    public List<Long> getOrderCodeByUser(List<Integer> userIds) {
        return orderSubscribeMapper.getOrderCodeByUsers(userIds);
    }

    @Override
    public List<OrderCarInfoAppDto> getUseCarIdByUser(Integer userId, Integer orderStatus) {
        return orderSubscribeMapper.getCarIdByUser(userId, orderStatus);
    }

    /**
     * 新增订阅里程订单
     *
     * @param createDto
     * @return id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Integer create(OrderSubscribeCreateDto createDto) {
        OrderSubscribeBean bean = Convert.toOrderSubscribeBean(createDto);
        orderSubscribeMapper.create(bean);
        return bean.getId();
    }

    /**
     * 订单状态修改
     *
     * @param orderCode      订单号
     * @param preOrderStatus 修改前状态
     * @param orderStatus    修改后状态
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Boolean modify(Long orderCode, OrderSubscribeStatusEnum preOrderStatus,
                          OrderSubscribeStatusEnum orderStatus) {
        if (orderSubscribeMapper.modifyStatus(orderCode, preOrderStatus.getValue(), orderStatus.getValue()) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 支付完成修改订阅订单
     *
     * @param modifyDto
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Boolean modifyPay(OrderPayModifyDto modifyDto) {
        if (orderSubscribeMapper.modifyPay(Convert.toOrderSubscribeBean(modifyDto),
                OrderSubscribeStatusEnum.TRADE_UNPAID.getValue(),
                OrderSubscribeStatusEnum.TRADE_CANCELED.getValue()) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 续订完成修改订单信息（是否有续订单改为有）
     *
     * @param orderCode 订单号
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Boolean modifyRenew(Long orderCode) {
        if (orderSubscribeMapper.modifyRenew(orderCode, true) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 统计排序订单商品销量
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getStatisticsGoods() {
        return orderSubscribeMapper.getStatisticsGoods();
    }

    /**
     * 提车完成修改订阅订单
     *
     * @param modifyDto
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Boolean modifyDelivery(OrderDeliveryModifyDto modifyDto) {
        if (orderSubscribeMapper.modifyDelivery(Convert.toOrderSubscribeBean(modifyDto),
                OrderSubscribeStatusEnum.TRADE_UNDELIVERY.getValue()) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 加购成功后修改订单预警里程
     *
     * @param orderCode       订单号
     * @param totalPayMileage 添加里程数
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Boolean modifyWarningMileageByPurchase(Long orderCode, Integer totalPayMileage) {
        if (orderSubscribeMapper.modifyWarningMileageByPurchase(orderCode, totalPayMileage,
                OrderSubscribeStatusEnum.TRADE_USE.getValue()) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 查询订阅里程订单待审核数量
     *
     * @return
     */
    @Override
    public Integer getOrderSubscribePendCount() {
        return orderSubscribeMapper.getOrderSubscribePendCount(OrderSubscribeStatusEnum.TRADE_UNAUDIT.getValue());
    }

    /**
     * 获取有效订阅续订订单信息（已支付）
     *
     * @param parentOrderCode 父订单号
     * @return
     */
    @Override
    public OrderSubscribeDto getEffectiveOrderSubscribeByParent(Long parentOrderCode) {
        OrderSubscribeDto result = null;
        List<OrderSubscribeBean> orderSubscribes = orderSubscribeMapper
                .getByParentOrderCode(parentOrderCode, null);
        if (orderSubscribes == null || orderSubscribes.isEmpty()) {
            return result;
        }
        for (OrderSubscribeBean orderSubscribeBean : orderSubscribes) {
            if (orderSubscribeBean.getOrderStatus() == OrderSubscribeStatusEnum.TRADE_UNAUDIT.getValue()
                    || orderSubscribeBean.getOrderStatus() == OrderSubscribeStatusEnum.TRADE_CANCELED.getValue()) {
                continue;
            }
            result = Convert.toOrderSubscribeBeanDto(orderSubscribeBean);
            break;
        }
        return result;
    }

    /**
     * 订阅超时未还车数量
     *
     * @return
     */
    @Override
    public Integer getSubscribeOvertimeCount() {
        return orderSubscribeMapper.getSubscribeOvertimeCount();
    }

    /**
     * 获取截止日未还车订单
     *
     * @param leaseExpire
     * @return
     */
    @Override
    public List<OrderSubscribeDto> getOrderExpire(LocalDate leaseExpire) {
        List<OrderSubscribeBean> orderSubscribes = orderSubscribeMapper.getOrderExpire(leaseExpire,
                OrderSubscribeStatusEnum.TRADE_USE.getValue());
        if (orderSubscribes == null || orderSubscribes.isEmpty()) {
            return null;
        }
        return Convert.toOrderSubscribeBeanDto(orderSubscribes);
    }

    /**
     * 订单结束时修改订阅订单
     *
     * @param modifyDto
     * @param oldStatus
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public boolean modifyFinish(OrderFinishModifyDto modifyDto, OrderSubscribeStatusEnum oldStatus) {
        if (orderSubscribeMapper.modifyFinish(Convert.toOrderSubscribeBean(modifyDto), oldStatus.getValue()) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 订单用车中修改
     *
     * @param modifyDto
     * @return
     */
    @Override
    public boolean modifyUse(OrderUseModifyDto modifyDto) {
        if (orderSubscribeMapper.modifyUse(Convert.toOrderSubscribeBean(modifyDto),
                OrderSubscribeStatusEnum.TRADE_UNUSE.getValue()) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 订单租期结束修改结束里程
     *
     * @param orderCode  订单号
     * @param endMileage 结束时里程
     * @return
     */
    @Override
    public boolean modifyEndMileageByExpire(Long orderCode, Integer endMileage) {
        if (orderSubscribeMapper.modifyEndMileageByExpire(orderCode, endMileage,
                OrderSubscribeStatusEnum.TRADE_USE.getValue()) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 查询最近N天，每天的订阅数量
     *
     * @param days
     * @return
     */
    @Override
    public Map<String, Integer> getSubscribeCountByDay(Integer days) {
        Map<String, Integer> baseMap = new HashMap();
        List<Map<String, Object>> baseList = orderSubscribeMapper.getSubscribeCountByDay(days);
        for (Map<String, Object> map : baseList) {
            String base = null;
            String fare = null;
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if ("key".equals(entry.getKey())) {
                    base = String.valueOf(entry.getValue());
                } else if ("value".equals(entry.getKey())) {
                    fare = String.valueOf(entry.getValue());
                }
                if (null == base) {
                    continue;
                }
                baseMap.put(base, Integer.valueOf(fare));
            }
        }
        return baseMap;
    }

    /**
     * 查询N天前的订阅订单数量
     *
     * @return
     */
    @Override
    public Integer getSubscribeYesterdayCount(Integer day) {
        Integer count = orderSubscribeMapper.getSubscribeYesterdayCount(day);
        return count == null ? 0 : count;
    }

    /**
     * 查询订阅订单中所有用车中的
     *
     * @return
     */
    @Override
    public List<OrderSubscribeDto> getSubscribeTradeUse() {
        return Convert.toOrderSubscribeBeanDto(orderSubscribeMapper.getSubscribeTradeUse(OrderSubscribeStatusEnum.TRADE_USE.getValue()));
    }

    /**
     * 查询专属订单信息
     *
     * @param payDate     支付日期
     * @param orderStatus 订单状态
     * @return
     */
    @Override
    public List<OrderSubscribeDto> getSubscribe(LocalDate payDate, OrderSubscribeStatusEnum orderStatus) {
        return Convert
                .toOrderSubscribeBeanDto(orderSubscribeMapper.getSubscribeByPayDate(payDate, orderStatus.getValue()));
    }

    /**
     * 查询不存在续订单的订阅订单
     *
     * @param leaseExpire
     * @param orderStatus
     * @return
     */
    @Override
    public List<OrderSubscribeDto> getNoneRenewable(LocalDate leaseExpire, OrderSubscribeStatusEnum orderStatus) {
        return Convert
                .toOrderSubscribeBeanDto(orderSubscribeMapper.getNoneRenewable(leaseExpire, orderStatus.getValue()));
    }

    /**
     * 订单还车修改订单
     *
     * @param modifyDto
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public Boolean modifyReturnCar(OrderReturnCarModifyDto modifyDto) {
        if (orderSubscribeMapper.modifyReturnCar(Convert.toOrderSubscribeBean(modifyDto),
                OrderSubscribeStatusEnum.TRADE_USE.getValue()) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 查询当天支付成功的
     *
     * @return
     */
    @Override
    public List<LocalDateTime> getTodaySubscribeCount() {
        return orderSubscribeMapper.getTodaySubscribeCount();
    }

    /**
     * 查询已提车的专属订单（包含已支付续订单）
     *
     * @return
     */
    @Override
    public Map<Integer, Integer> getEffectiveOrderVehicleStatistics() {
        Map<Integer, Integer> result = null;
        // 查询不是取消状态且提车的订单
        List<Map<String, Object>> list = orderSubscribeMapper.getEffectiveOrderVehicleStatistics(OrderExclusivelStatusEnum.TRADE_CANCELED.getValue());
        if (list == null || list.isEmpty()) {
            return result;
        }
        result = new HashMap<>();
        for (Map<String, Object> map : list) {
            Integer vehicleId = map.get("vehicleId") == null ? null : Integer.parseInt(map.get("vehicleId").toString());
            Integer ordersCount = map.get("ordersCount") == null ? null : Integer.parseInt(map.get("ordersCount").toString());
            result.put(vehicleId, ordersCount);
        }

        return result;
    }

    /**
     * 查询每个门店下生效订单（提车、续订生效）数量
     *
     * @return
     */
    @Override
    public Map<Integer, Integer> getEffectiveOrderStoreStatistics() {
        Map<Integer, Integer> result = null;
        // 查询不是取消状态且提车的订单
        List<Integer> effectiveStatusList = OrderStatusConst.SUBSCRIBE_EFFECTIVE_STATUS.stream().map(orderStatus -> {
            return orderStatus.getValue();
        }).collect(Collectors.toList());
        List<Map<String, Object>> list = orderSubscribeMapper.getEffectiveOrderStoreStatistics(effectiveStatusList);
        if (list == null || list.isEmpty()) {
            return result;
        }
        result = new HashMap<>();
        for (Map<String, Object> map : list) {
            Integer vehicleId = map.get("storeId") == null ? null : Integer.parseInt(map.get("storeId").toString());
            Integer ordersCount = map.get("ordersCount") == null ? null : Integer.parseInt(map.get("ordersCount").toString());
            result.put(vehicleId, ordersCount);
        }

        return result;
    }

    /**
     * 查询统计每种商品已支付的订阅订单
     *
     * @return
     */
    @Override
    public List<GoodsSalesStatisticsBizDto> getEffectiveOrderGoodsStatistics() {
        List<Map<String, Object>> mapList = orderSubscribeMapper.getEffectiveOrderGoodsStatisticsWherePay(
                OrderSubscribeStatusEnum.TRADE_CANCELED.getValue());
        if (mapList == null || mapList.isEmpty()) {
            return null;
        }
        List<GoodsSalesStatisticsBizDto> result = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            GoodsSalesStatisticsBizDto dto = new GoodsSalesStatisticsBizDto();
            dto.setGoodsId(Integer.parseInt(map.getOrDefault("goodsId", "0").toString()));
            dto.setPackageMileageId(Integer.parseInt(map.getOrDefault("packageMileageId", "0").toString()));
            dto.setVehicleId(Integer.parseInt(map.getOrDefault("vehicleId", "0").toString()));
            dto.setSales(Integer.parseInt(map.getOrDefault("sales", "0").toString()));
            dto.setGoodsName(map.getOrDefault("transportTime", "0") + "月-"
                    + map.getOrDefault("baseMileage", "0") + "km-"
                    + map.getOrDefault("packageMileage", "0") + "km");

            result.add(dto);
        }

        result = result.stream().sorted(Comparator.comparing(GoodsSalesStatisticsBizDto::getSales).reversed())
                .collect(Collectors.toList());

//        // 查询所有已支付未取消的专属订单信息
//        List<OrderSubscribeBean> beans = orderSubscribeMapper.getHavePaidOrder(
//                OrderSubscribeStatusEnum.TRADE_CANCELED.getValue());
//        if (beans == null || beans.isEmpty()) {
//            return null;
//        }
//        Map<String, GoodsSalesStatisticsBizDto> map = new HashMap<>();
//        beans.forEach(bean -> {
//            String key = bean.getGoodsId() + "_" + bean.getPackageMileageId();
//            GoodsSalesStatisticsBizDto dto = map.get(key);
//            if (dto == null) {
//                dto = new GoodsSalesStatisticsBizDto();
//                Convert.toGoodsSalesStatisticsBizDto(bean);
//            } else {
//                dto.setSales(dto.getSales() + 1);
//            }
//        });

        return result;
    }

}
